#!/usr/bin/env python
# coding=utf-8

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

from vavava import dbworkshop
from spiders.dhl import fetcher_dhl,taskwork_dhl
from spiders.auspost import fetcher_auspost,taskwork_auspost
from spiders.tnt import fetcher_tnt
from spiders.tnt_inter import fetcher_tnt_inter

def dhl_test(dbws,conn,log):
    fetcher = fetcher_dhl.fetcher_dhl(item_id="8253917394", log=log )
    fetcher.SetDBConn(conn)
    fetcher.Fetch()

def auspost_test(dbws,conn,log):
    fetcher = fetcher_auspost.FetcherAuspost(item_id="UCL0007155", log=log )
    fetcher.SetProxy({"http":"http://127.0.0.1:8087"})
    fetcher.SetDBConn(conn)
    fetcher.Fetch()

def tnt_test(dbws,conn,log):
    fetcher = fetcher_tnt.FetcherTnt(item_id="435876560", log=log )
    fetcher.SetDBConn(conn)
    fetcher.Fetch()

def tnt_inter_test(dbws,conn,log):
    fetcher = fetcher_tnt_inter.FetcherTntInter(item_id="437881275", log=log )
    fetcher.SetDBConn(conn)
    fetcher.Fetch()

def work_test(dbws,conn,log):
    dhl = taskwork_dhl.DhlWork(item_id="8253917394",group=None,log=log)
    auspost = taskwork_auspost.AuspostWork(
        item_id="UCL0007155",
        group=None,
        log=log,
        proxy={"http":"http://127.0.0.1:8087"}
    )
    au_task = taskwork_auspost.AuspostTaskWork(period=3600,group=None)
    #dbws.QueueWork(dhl)
    #dbws.QueueWork(auspost)
    dbws.QueueWork(au_task)




if __name__ == '__main__':
    from DBUtils import PooledDB
    from vavava import util
    import MySQLdb,time,os
    # init log
    log = util.initlog("./log/"+ os.path.split(__file__)[1]+".log")
    # init db conn
    dbpool = PooledDB.PooledDB(
        MySQLdb,11,22,11,22,False,host='localhost',user='tracker',passwd='123',db='tracking', charset='utf8' )
    conn = dbpool.connection()
    # init dbworkshop
    dbws = dbworkshop.DBWorkshop(dbpool=dbpool,minsize=2,log=log)

    display_str="""test Begin[%s]"""
    log.info(display_str%(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))))
    try:
        # 开始工作 ===============================================================
        dbws.StartWork()
        dhl_test(dbws,conn,log)

        # 工作完成 ===============================================================

        while True:
            time.sleep(3)
        log.info('main thread(%s):stopped'%
                 time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))
    except(KeyboardInterrupt):
        print('main thread(%f): User canceled by Ctrl-c'%time.clock())
    finally:
        print('main thread(%f):stop'%time.clock())
        if dbws.IsAlive:
            dbws.StopWork(timeout=30)
        log.info('main thread(%s):stopped'%
                 time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))
